//
//  WOTableViewController.m
//
//  Created by Olof Millberg on 2010-04-14.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WOTableViewController.h"
#import "WOTableSection.h"
#import "WOTableViewCell.h"

@implementation WOTableViewController

@synthesize workOrder;
@synthesize sections;

#pragma mark Initialization Methods

/* Get instace of class */
- (id) initWithWorkOrder:(WorkOrder *)aWorkOrder
{
	if (self = [self init])
	{
		self.workOrder = aWorkOrder;
		
	}
	return self;
}

/* Dellaocate stuff */
- (void) dealloc
{
	[workOrder release];
	[sections release];
	[super dealloc];
}

#pragma mark -

#pragma mark UITableView Methods

/* Returns the identifier of a row at index path */
- (NSString *) identifierAtIndexPath:(NSIndexPath *)indexPath
{
	WOTableSection *section = [sections objectAtIndex:indexPath.section];
	return [section identifierAtRow:indexPath.row];
}

/* Returns the number of sections in the table */
- (NSInteger) numberOfSectionsInTableView:(UITableView *)aTableView
{
	return sections.count;
}

/* Returns the number of rows in a given section */
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{
	return ((WOTableSection *)[sections objectAtIndex:section]).numberOfRows;
}

/* Returns a cell for a given index path */
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{		
	NSString *identifier = [self identifierAtIndexPath:indexPath];
	
	UITableViewCell *cell = (UITableViewCell*)[aTableView dequeueReusableCellWithIdentifier:identifier];
	if (!cell) 
	{
		if ([identifier isEqualToString:@"BaseCell"])
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BaseCell"] autorelease];
		else
		{
			NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
			
			for (id currentObject in topLevelObjects) 
			{
				if ([currentObject isKindOfClass:[UITableViewCell class]])
				{
					cell = currentObject;
					break;
				}
			}
		}
		//cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	
	if ([cell isKindOfClass:[WOTableViewCell class]])
		[(WOTableViewCell*)cell populateWithDataFromWorkOrder:self.workOrder];
	
	return cell;
}

/* Returns the title for a given section */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return ((WOTableSection*)[sections objectAtIndex:section]).title;
}

/* Returns the height for the row at a given index path */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (!sections)
		return tableView.rowHeight;
	return [((WOTableSection*)[sections objectAtIndex:indexPath.section]) heightForRow:indexPath.row];
}

#pragma mark -

@end